<!--  -->
<template>
  <div class="cycle_label_multiple">
    <div class="label_multiple_header" slot="label">
      <el-switch
        v-model="dataForm[scriptItem.text + 'Flag']"
        active-color="#138DC7"
        inactive-color="#BFBFBF"
      ></el-switch>
    </div>
    <div class="lable_content">{{ scriptItem.content }}</div>
    <div class="cycleMultiple" v-if="dataForm[scriptItem.text + 'Flag']">
      <div
        v-for="(items, index) in dataForm[scriptItem.text]"
        :key="index"
        class="for-item cycle_multiple_cont"
      >
        <div class="triggedWrap">
          <div class="Multiplelist_label">
            <div class="Multiplelist_label_header">
              <div class="label_header_lf">
                <span
                  :class="
                    !items.dis ? 'el-icon-arrow-down' : 'el-icon-arrow-right'
                  "
                  style="margin-right: 5px"
                  @click="openContent(items, index)"
                ></span>
                <span class="laber_text"
                  >{{ $t('statement.es') }}&nbsp;&nbsp;{{ index + 1 }}</span
                >
              </div>
              <div class="label_header_rg">
                <el-button
                  circle
                  plain
                  size="mini"
                  @click="deleteModuleItem(index)"
                ></el-button>
              </div>
            </div>
            <div class="Multiplelist_label_content">
              <span>{{ scriptItem.beforeText }}</span>
              <el-input-number
                v-model="items[scriptItem.numberFields]"
                class="inputNumber"
                size="mini"
                style="margin: 0 5px"
                controls-position="right"
                :min="scriptItem.minNumber"
                :max="scriptItem.maxNumber"
              ></el-input-number>
              <span>{{ scriptItem.middleText }}</span>
              <el-select
                v-model="items[scriptItem.dateFields]"
                @change="changeNumebrAndDate"
                size="mini"
                style="margin: 0 5px; width: 100px"
                :disabled="index !== 0"
              >
                <el-option
                  v-for="(item, index) in scriptItem.selectList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <span>{{ scriptItem.afterText }}</span>
              <!-- <span class="font_weight"></span>
            <span>( who selected in Alert)</span> -->
              <!-- <span class="font_weight">{{formchran(items.managerList)}}.</span> -->
            </div>
          </div>
        </div>
        <div class="Multiplelist" v-show="!items.dis">
          <div
            v-for="(item, i) in items[scriptItem.templateMultipleText]"
            :key="i"
            class="for-item"
          >
            <el-form :inline="true">
              <el-form-item
                class="form_list_template"
                style="display: inline-block"
                :label-width="`${scriptItem.templateLabelWidth}px`"
              >
                <el-dropdown
                  trigger="click"
                  v-if="scriptItem.text.includes('teams')"
                  style="margin-left: 15px; margin-top: 10px; height: 20px"
                  @visible-change="
                    handleDropdownOptionDisabled($event, item, items, i)
                  "
                  @command="handleCommand"
                >
                  <span class="el-dropdown-link">
                    {{
                      item.manager ? transformatLabel(item.manager) : 'Select'
                    }}
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      :command="{
                        parentIndex: index,
                        index: i,
                        item: item,
                        label: list[scriptItem.toFieldValue]
                      }"
                      v-for="(list, is) in item.toDataList"
                      :disabled="list.disabled"
                      :key="is"
                      >{{ list[scriptItem.toFieldLabel] }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
                <div
                  :class="[
                    scriptItem.text.includes('teams')
                      ? 'item_template_box_teams'
                      : 'item_template_box_email'
                  ]"
                >
                  <div
                    v-for="(itemChild, iii) in scriptItem.contentType"
                    :key="iii"
                    class="item_template"
                    style="margin-left: 20px"
                  >
                    <TypeSendMessageBcc
                      v-if="itemChild.type === 'send-message'"
                      :onlyShowUserList="
                        scriptItem.text.includes('teams') ? true : false
                      "
                      :dataForm="item"
                      :scriptItem="itemChild"
                    >
                    </TypeSendMessageBcc>
                    <TypeTemplate
                      v-if="itemChild.type === 'select-template'"
                      :dataForm="item"
                      @hiddenSettingModel="hiddenSettingModels"
                      :blockInfo="blockInfo"
                      :labelInfo="scriptItem.label"
                      :scriptItem="itemChild"
                    ></TypeTemplate>
                    <TypeText
                      v-if="itemChild.type === 'text'"
                      :dataForm="item"
                      :scriptItem="itemChild"
                    />
                  </div>
                </div>
                <div
                  class="deleteTemplate cursor_pointer"
                  style="margin-top: 10px"
                  @click="
                    deleteItem(
                      i,
                      items[scriptItem.templateMultipleText],
                      items,
                      index
                    )
                  "
                ></div>
              </el-form-item>
            </el-form>
            <div
              class="editor_content"
              v-if="scriptItem.text.includes('teams')"
            >
              <ZTinymce
                v-model="item[scriptItem.templateFields]"
                :ref="`myTextEditor${index}${i}`"
                @change="html => onMessageChange(html, item)"
                :height="50"
                :theme="item.modeType"
              />

              <div class="insert-token">
                <el-tooltip
                  :open-delay="1000"
                  class="item"
                  effect="dark"
                  :content="$t('statement.iat')"
                  placement="top"
                >
                  <el-popover
                    placement="top"
                    trigger="click"
                    popper-class="insert_token_pop"
                    width="380"
                  >
                    <div
                      v-if="!isShowChild && !isShowChildDrillThrough"
                      style="
                        color: #000;
                        font-size: 16px;
                        font-weight: 600;
                        margin-bottom: 10px;
                      "
                    >
                      {{ $t('statement.dt') }}
                    </div>
                    <div
                      v-else
                      class="cursor_pointer"
                      style="
                        color: #000;
                        font-size: 16px;
                        font-weight: 600;
                        margin-bottom: 10px;
                      "
                      @click="gotoback"
                    >
                      <i class="el-icon-arrow-left"></i>&nbsp;&nbsp;{{
                        $t('statement.fn')
                      }}
                    </div>
                    <el-input
                      v-if="!isShowChild && !isShowChildDrillThrough"
                      v-model="searchToken"
                      prefix-icon="el-icon-search"
                      :placeholder="$t('placeholder.search')"
                      @input="getFilterTokenList"
                      size="small"
                      style="margin-bottom: 10px"
                    ></el-input>
                    <el-input
                      v-if="isShowChild || isShowChildDrillThrough"
                      v-model="searchTokenchild"
                      prefix-icon="el-icon-search"
                      :placeholder="$t('placeholder.search')"
                      @input="getFilterTokenchildList"
                      size="small"
                      style="margin-bottom: 10px"
                    ></el-input>
                    <div
                      v-if="
                        isTipsShow && !isShowChild && !isShowChildDrillThrough
                      "
                      style="height: 50px; backgroundcolor: #e6f7ff"
                    >
                      <div
                        style="
                          float: left;
                          width: 90%;
                          color: #138dc7;
                          line-height: 20px;
                          padding: 5px;
                          padding-left: 9px;
                          word-break: break-word;
                        "
                      >
                        {{ $t('statement.adtfd') }}
                      </div>
                      <i
                        @click="isTipsShow = false"
                        class="el-icon-close cursor_pointer"
                        style="
                          float: right;
                          color: #138dc7;
                          margin: 8px 9px 0 0;
                        "
                      ></i>
                    </div>
                    <el-alert
                      v-if="
                        !(
                          filterTokenList.length > 0 &&
                          filterTokenList[0].fieldsList.length > 0
                        ) && !drillThroughFieldsListarr.length > 0
                      "
                      style="margin-top: 10px"
                      :closable="false"
                      center
                      :title="$t('statement.nmd')"
                      type="info"
                    ></el-alert>
                    <div
                      class="token-list"
                      v-if="
                        filterTokenList.length > 0 &&
                        filterTokenList[0].fieldsList.length > 0
                      "
                    >
                      <div
                        class="token-list-item"
                        v-for="(item, index222) in filterTokenList"
                        :key="index222"
                      >
                        <div v-if="!isShowChild && !isShowChildDrillThrough">
                          <div
                            class="group-title"
                            style="backgroundcolor: #f0f0f0; padding-left: 9px"
                            :style="{ 'margin-top': isTipsShow ? '10px' : 0 }"
                          >
                            {{ $t('statement.dsf') }}
                          </div>
                          <div style="max-height: 150px; overflow: auto">
                            <div
                              class="group-item"
                              v-for="(its, ii) in item.fieldsList"
                              :key="ii"
                              @click="
                                its.type === 'user'
                                  ? openChild(its)
                                  : clickToken(its, index, i)
                              "
                            >
                              <span
                                :style="{
                                  'font-weight':
                                    its.type === 'user' ? '600' : '400'
                                }"
                                >{{
                                  its.type === 'user'
                                    ? its.label.replace(/[\{\}]/g, '')
                                    : its.label
                                }}</span
                              >
                              <i
                                v-if="its.type === 'user'"
                                class="el-icon-arrow-right"
                                style="float: right; padding-top: 10px"
                              ></i>
                            </div>
                          </div>
                        </div>
                        <div v-if="isShowChild && !isShowChildDrillThrough">
                          <div
                            class="group-item"
                            v-for="(its, e) in filteruserfieldsList"
                            :key="e"
                            @click="clickTokenchild(its, null, index, i)"
                          >
                            {{ its.label }}
                          </div>
                        </div>
                      </div>
                    </div>
                    <div
                      class="token-list"
                      v-if="drillThroughFieldsListarr.length > 0"
                    >
                      <div class="token-list-item">
                        <div v-if="!isShowChild && !isShowChildDrillThrough">
                          <div
                            class="group-title"
                            style="backgroundcolor: #f0f0f0; padding-left: 9px"
                          >
                            {{ $t('statement.dtf') }}
                          </div>
                          <div style="max-height: 150px; overflow: auto">
                            <div
                              class="group-item11"
                              v-for="(its, ii) in drillThroughFieldsListarr"
                              :key="ii"
                              @click="openChildDrillThrough(its, ii)"
                            > 
                             <ZTooltip :content="its.datasetName"
                              :line="1"
                              placement="right">
                               <span style="font-weight: 600;">{{
                                its.datasetName
                               }}</span>
          
                              </ZTooltip>
                             
                              <i
                                class="el-icon-arrow-right"
                                style="float: right; padding-top: 10px"
                              ></i>
                            </div>
                          </div>
                        </div>
                        <div
                          v-if="!isShowChild && isShowChildDrillThrough"
                          style="max-height: 442px; overflow: auto"
                        >
                          <div
                            class="group-item"
                            v-for="(its, ee) in childDrillThroughfieldsList"
                            :key="ee"
                            @click="clickTokenchild(its, true, index, i)"
                          >
                            {{ its.label }}
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="token-list"
                        v-if="ancestorsTokenList.length>0&&!isShowChildDrillThrough">
                      <div class="token-list-item">
                        <div v-for="item in ancestorsTokenList" :key="item.id">
                          <div class="group-title"
                              style="backgroundColor:#F0F0F0;padding-left:9px;"
                              :style="{'margin-top':isTipsShow?'10px':0}">{{item.name}}</div>
                          <div class="group-item"
                              v-for="its in item.tokenList"
                              :key="its.value"
                              @click="clickToken(its, index, i)">{{ its.label }}
                          </div>
                        </div>
                      </div>
                    </div>
                    <el-button
                      size="mini"
                      type="primary"
                      plain
                      slot="reference"
                      style="padding: 7px; border: none"
                    >
                      <span
                        class="cuifont icon_insert_token"
                        style="fontsize: 14px"
                      ></span>
                    </el-button>
                  </el-popover>
                </el-tooltip>
              </div>
              <div class="editor_content_template">
                <el-dropdown @command="val => handleCommandPreview(val, item)">
                  <span class="el-dropdown-link">
                    {{ item.mode || 'Light Mode'
                    }}<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="lightmode"
                      >Light Mode</el-dropdown-item
                    >
                    <el-dropdown-item command="darkmode"
                      >Dark Mode</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
                <div>
                  <label for="">{{ $t('statement.ct') }} &nbsp;</label>
                  <el-select
                    v-model="item['TemplateIds']"
                    filterable
                    clearable
                    @change="templateIdChange($event, item, index, i)"
                    :placeholder="scriptItem.templateHint"
                    default-first-option
                  >
                    <el-option
                      v-for="(o, ii) in filterSelect(
                        selectDataObj[`${scriptItem.text}ListsOrigin`]
                      )"
                      :key="ii"
                      :label="o[scriptItem.templateFieldLabel]"
                      :value="o[scriptItem.templateFieldValue]"
                    ></el-option>
                  </el-select>
                </div>
                <div>
                  <el-popover
                    placement="top"
                    width="205"
                    @hide="clearPopover(i)"
                    :ref="`editTemplatePopover-${index}${i}`"
                  >
                    <el-form
                      :model="editTemplateForm"
                      :rules="dataRule"
                      size="mini"
                      ref="template-form"
                      label-position="top"
                    >
                      <el-form-item :label="$t('label.tn')" prop="name">
                        <el-input
                          v-model="editTemplateForm.name"
                          :placeholder="$t('placeholder.pe')"
                        ></el-input>
                      </el-form-item>
                      <el-form-item :label="$t('label.tt')" prop="type">
                        <el-select
                          v-model="editTemplateForm.type"
                          :placeholder="$t('placeholder.ps')"
                        >
                          <el-option
                            v-for="(its, ie) in ['teams_message', 'email']"
                            :key="ie"
                            :label="its"
                            :value="its"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item>
                        <el-checkbox v-model="viewTemplatePage">{{
                          $t('statement.vaa')
                        }}</el-checkbox>
                      </el-form-item>
                    </el-form>
                    <div class="popover-footer-btn">
                      <el-button
                        size="mini"
                        @click="editTemplatePopoverCloese(index, i)"
                        >{{ $t('attribute.close') }}</el-button
                      >
                      <el-button
                        size="mini"
                        type="primary"
                        :loading="addBtnLoading"
                        @click="
                          addMessageTemplate(i, item[scriptItem.templateFields])
                        "
                        >{{ $t('attribute.add') }}</el-button
                      >
                    </div>
                    <el-button
                      size="mini"
                      type="primary"
                      plain
                      style="margin-right: 15px; padding: 7px; border: none"
                      slot="reference"
                    >
                      <span
                        class="cuifont icon_save_edit"
                        style="fontsize: 14px"
                      >
                        {{ $t('statement.template') }}</span
                      >
                    </el-button>
                  </el-popover>
                </div>
              </div>
            </div>
          </div>
          <div class="Multiplelist_form_list">
            <div
              class="add_message"
              @click="addItem(index, items[scriptItem.templateMultipleText])"
            >
              <span class="">{{ $t('statement.am') }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="add_new_program">
        <el-button
          type="primary"
          icon="el-icon-plus"
          circle
          size="mini"
          @click="addModuleItem"
          >{{ $t('statement.an') }}</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import mixinTypeViewModule from '@/mixins/script-type-view-module'
import TypeTemplate from './type-select-template'
import { debounce } from 'lodash'
import TypeSendMessageBcc from './type-send-message-bcc'
import TypeText from './type-text'
// import { debounce } from 'lodash'
import ZTooltip from '@/components/storybook/z-tooltip'
import ZTinymce from '@/components/storybook/z-tinymce/index.vue'
import { findAncestors } from '@/utils/common'
export default {
  mixins: [mixinTypeViewModule],
  components: { TypeTemplate, TypeSendMessageBcc, TypeText, ZTinymce,ZTooltip },
  props: {
    blockInfo: {
      type: Object,
      default: () => {}
    }
  },
  inject: { 
    blockDataSource: { default: () => [] },
   },
  data() {
    return {
      visible: false,
      priviewMessage: null,
      switchPreview: false,
      parentChangeIndex: 0,
      priviewChecked: false,
      emailList: [],
      editorOption: {
        name: '471',
        modules: {
          toolbar: [
            ['code-block'],
            [{ direction: 'rtl' }],
            ['bold', 'italic', 'underline', 'strike'],
            [{ color: [] }],
            [{ background: [] }],
            [{ header: 1 }, { header: 2 }],
            [{ script: 'sub' }, { script: 'super' }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            [{ font: ['sans-serif', 'monospace', 'serif'] }],
            [{ size: ['small', false, 'large', 'huge'] }],
            [{ align: [] }],
            ['link'],
            ['clean']
          ]
        },
        theme: 'snow',
        placeholder: ''
      },
      forLists: this.scriptItem.toDataList || [],
      searchToken: null,
      filterTokenList: [],
      editTemplateForm: {
        name: null,
        type: null
      },
      viewTemplatePage: false,
      addBtnLoading: false,
      insertTokenPopover: false,
      editTemplatePopover: false,
      popIndex: 0,
      dataRule: {
        name: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur',
            pattern: '[^ \x22]+'
          },
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        type: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ]
      },
      isShowChild: false,
      isTipsShow: true,
      drillThroughFieldsListarr: [],
      filteruserfieldsList: [],
      fatherfield: null,
      isShowChildDrillThrough: false,
      userfieldsList: [
        { label: '{{headUrl}}', value: 'headUrl' },
        { label: '{{email}}', value: 'email' },
        { label: '{{firstName}}', value: 'firstName' },
        { label: '{{lastName}}', value: 'lastName' },
        { label: '{{fullName}}', value: 'fullName' }
      ],
      ancestorsTokenList: [],
    }
  },
  watch: {
    isShowChild(val) {
      if (!val) {
        this.searchTokenchild = null
        this.resetFilterTokenchildList(this.searchTokenchild)
      }
    },
    isShowChildDrillThrough(val) {
      if (!val) {
        this.searchTokenchild = null
        this.resetFilterTokenchildList(this.searchTokenchild)
      }
    },
    insertTokenPopover: {
      handler: function (val) {
        if (val) {
          this.isTipsShow = true
          document.addEventListener('mousedown', this.mouseDownListener)
        } else {
          document.removeEventListener('mousedown', this.mouseDownListener)
          this.searchToken = null
          this.resetFilterTokenList(this.searchToken)
          this.searchTokenchild = null
          this.resetFilterTokenchildList(this.searchTokenchild)
          this.isShowChild = false
          this.isShowChildDrillThrough = false
        }
      },
      immediate: true
    },
    editTemplatePopover: {
      handler: function (val) {
        if (val) {
          document.addEventListener('mousedown', this.mouseDownListener)
        } else {
          document.removeEventListener('mousedown', this.mouseDownListener)
        }
      },
      immediate: true
    }
  },
  computed: {
    comScriptItem() {
      return {
        ...this.scriptItem,
        fieldLabel: this.scriptItem.templateFieldLabel,
        fieldValue: this.scriptItem.templateFieldValue
      }
    },
    comTextareaWidth() {
      try {
        let width =
          70 +
          20 +
          Number(this.scriptItem.toLabelWidth) +
          Number(this.scriptItem.toFieldsWidth) +
          Number(this.scriptItem.templateLabelWidth) +
          Number(this.scriptItem.templateFieldsWidth)
        return width
      } catch (error) {
        return 'auto'
      }
    }
  },
  created() {
    try {
      if (this.blockDataSource) {
        const ancestors = findAncestors(this.blockDataSource(), this.blockInfo.id);
        let res = ancestors.filter(e => e?.paramsJson?.tokenList)
        this.ancestorsTokenList = res.map(e => {
          return {
            name:e.name,
            tokenList: e.paramsJson.tokenList.map(v=>{
              return {
                label: `{{${v.label}}}`,
                value: v.value
              }
            })
          }
        })
      }
    } catch (error) {

    }
    let _self = this
    try {
      _self.dataForm[_self.scriptItem.text].forEach(item => {
        if (!item[_self.scriptItem['dateFields']]) {
          _self.$set(
            item,
            _self.scriptItem['dateFields'],
            _self.dataForm[_self.scriptItem['dateFields']] || 'day'
          )
        }
      })
    } catch (error) {}
    this.getTokenList()
    this.filteruserfieldsList = this.userfieldsList
  },
  methods: {
    hiddenSettingModels() {
      this.$emit('hiddenSettingModel')
    },
    changeNumebrAndDate() {
      this.$forceUpdate()
      this.dataForm[this.scriptItem.text].forEach((item, index) => {
        if (index !== 0) {
          item[this.scriptItem.dateFields] =
            this.dataForm[this.scriptItem.text][0][this.scriptItem.dateFields]
        }
      })
    },
    handleCommandPreview(val, item) {
      item.mode = val === 'lightmode' ? 'Light Mode' : 'Dark Mode'
      item.modeType = val
      this.$forceUpdate()
    },
    clickTokenchild(its, isDrillThrough, index, i) {
      if (isDrillThrough) {
        this.insertFields(`${this.fatherfield}#${its.value}`, index, i)
      } else {
        this.insertFields(`${this.fatherfield}.${its.value}`, index, i)
      }
    },
    mouseDownListener(event) {
      if (!event.target.closest('.block-model-dialog')) {
      } else {
        this.insertTokenPopover = false
        this.editTemplatePopover = false
      }
    },
    openChildDrillThrough(its, index) {
      this.fatherfield = its.datasetName
      this.isShowChildDrillThrough = true
      this.childDrillThroughfieldsListarr =
        this.drillThroughFieldsListarr[index].data
      this.childDrillThroughfieldsList = this.childDrillThroughfieldsListarr
    },
    getFilterTokenList: debounce(function (val) {
      this.resetFilterTokenList(val)
    }, 800),
    getFilterTokenchildList: debounce(function (val) {
      this.resetFilterTokenchildList(val)
    }, 800),
    clickToken(its, index, i) {
      // if (!(this.dataForm[`${this.scriptItem.datasetKeyStore}UseFidld`].find(item => item.field === its.value))) {
      //   this.dataForm[`${this.scriptItem.datasetKeyStore}UseFidld`].push({
      //     field: its.value,
      //     dbType: its.type
      //   })
      // }
      this.insertFields(its.value, index, i)
    },
    resetFilterTokenchildList(val) {
      let searchVal = val || this.searchTokenchild
      if (searchVal) {
        let copyData = this._.cloneDeep(this.userfieldsList)
        copyData = copyData.filter(its =>
          its.label.toLowerCase().includes(searchVal.toLowerCase())
        )
        this.filteruserfieldsList = copyData
      } else {
        this.filteruserfieldsList = this.userfieldsList
      }
      if (searchVal) {
        let copyData = this._.cloneDeep(this.childDrillThroughfieldsListarr)
        copyData = copyData.filter(its =>
          its.label.toLowerCase().includes(searchVal.toLowerCase())
        )
        this.childDrillThroughfieldsList = copyData
      } else {
        this.childDrillThroughfieldsList = this.childDrillThroughfieldsListarr
      }
    },
    openChild(its) {
      this.fatherfield = its.value
      this.isShowChild = true
    },
    gotoback() {
      this.isShowChild = false
      this.isShowChildDrillThrough = false
    },
    filterSelect(arr) {
      if (!arr) {
        arr = []
      }
      var temp = arr.filter(item => {
        return item.name.includes('Escalation-')
      })
      temp = temp.sort(function (a, b) {
        return a.name.length - b.name.length
      })
      temp = temp.sort(function (a, b) {
        if (a.name.length === b.name.length) {
          return a.name.localeCompare(b.name)
        }
      })
      return temp
    },
    onMessageChange(html, item) {
      item['priviewMessage'] = html

      this.$forceUpdate()
    },
    formchran(str) {
      let arr = str.split(',')
      let returnStr = []
      this.scriptItem.defaultValue[0].templateList[0].toDataList.forEach(
        element => {
          if (arr.includes(element.value)) returnStr.push(element.label)
        }
      )
      return returnStr.join(' , ')
    },
    editTemplateReturn(i) {
      // return `editTemplatePopover${i}`
      this.$set(this, `editTemplatePopover${i}`, false)
      return this[`editTemplatePopover${i}`]
      // return `editTemplatePopover`
    },
    editTemplatePopoverCloese(index, i) {
      this.$refs[`editTemplatePopover-${index}${i}`][0].doClose()
    },
    addMessageTemplate(index, ItemTemplate) {
      this.$refs['template-form'][index].validate(valid => {
        if (!valid) {
          return false
        }
        this.addBtnLoading = true
        const params = {
          template: ItemTemplate || '',
          ...this.editTemplateForm
        }
        this.$interface.schedule
          .saveTemplateInfoApi(params)
          .then(({ data: res }) => {
            this.addBtnLoading = false
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.$message.success(res.msg)
            this.editTemplatePopover = false
            this.init()
            this.viewTemplatePage && this.routerToTemplatePage()
          })
          .catch(() => {
            this.addBtnLoading = false
          })
      })
    },
    clearPopover(index) {
      this.$refs['template-form'][index].resetFields()
      this.viewTemplatePage = false
    },

    insertFields(value, index, i) {
      if (!value) {
        return false
      }
      this.$refs[`myTextEditor${index}${i}`][0].focus()
      const range = this.$refs[`myTextEditor${index}${i}`][0].getRng()

      const node = document.createElement('span')
      node.innerHTML = `<span>&nbsp;&nbsp;</span><strong style="color:#17B3A3">{{${value}}}</strong><span>&nbsp;&nbsp;</span>`

      range.insertNode(node)
    },
    getTokenList() {
      let id = this.$store.state.bot.id
      let type = this.$store.state.bot.type
      this.tokenList = []
      if (!id) {
        return
      }
      const params = {}
      type === 'dataset' && (params['datasetId'] = id)
      type === 'widget' && (params['gadgetId'] = id)
      params.showColumn = true
      this.$interface.reports.getFieldsListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.tokenList = []
            return false
          }
          if (res.querySelectedColumns) {
            this.dataForm.resultValue = res.querySelectedColumns
            this.drillThroughFieldsList = res.querySelectedColumns
            this.drillThroughFieldsList.forEach(item => {
              item.data.forEach(its => {
                its.label = `{{${its.alias}}}`
                its.value = its.alias
              })
            })
            this.drillThroughFieldsListarr = this.drillThroughFieldsList
          }
          let tempList = []
          res.data.forEach(item => {
            if (item.type === 'user') {
              tempList.unshift({
                label: `{{${item.name}}}`,
                value: item.name,
                type: item.type
              })
            } else {
              tempList.push({
                label: `{{${item.name}}}`,
                value: item.name,
                type: item.type
              })
            }
          })
          this.tokenList.push({
            name: this.$store.state.bot.name,
            fieldsList: tempList
          })
          this.$nextTick(() => {
            this.resetFilterTokenList()
          })
      }).catch(() => {
        this.tokenList = []
      })
    },
    tokenListHide() {
      this.searchToken = ''
    },
    tokenListShow(index) {
      this.popIndex = index
    },
    resetFilterTokenList(val) {
      let searchVal = val || this.searchToken
      if (searchVal) {
        let copyData = this._.cloneDeep(this.tokenList)
        for (let i = 0; i < copyData.length; i++) {
          copyData[i].fieldsList = copyData[i].fieldsList.filter(its =>
            its.label.toLowerCase().includes(searchVal.toLowerCase())
          )
        }
        this.filterTokenList = copyData || []
      } else {
        this.filterTokenList = this.tokenList || []
      }
      if (searchVal) {
        let copyData = JSON.parse(JSON.stringify(this.drillThroughFieldsList))
        copyData = copyData.filter(its =>
          its.datasetName.toLowerCase().includes(searchVal.toLowerCase())
        )
        this.drillThroughFieldsListarr = copyData || []
      } else {
        this.drillThroughFieldsListarr = this.drillThroughFieldsList || []
      }
    },
    returnAllManager(item) {
      item.managerList = ''
      let str = ''
      item[this.scriptItem.templateMultipleText].forEach(element => {
        if (element.manager) str += element.manager + ','
      })
      this.$set(item, 'managerList', str)
    },
    handleCommand(command) {
      this.parentChangeIndex = command.parentIndex
      this.$set(
        this.dataForm[this.scriptItem.text][command.parentIndex][
          this.scriptItem.templateMultipleText
        ][command.index],
        'manager',
        command.label
      )
      this.$set(
        this.dataForm[this.scriptItem.text][command.parentIndex][
          this.scriptItem.templateMultipleText
        ][command.index],
        'disabled',
        true
      )
      this.returnAllManager(
        this.dataForm[this.scriptItem.text][command.parentIndex]
      )
    },
    transformatLabel(manager) {
      let label = ''
      switch (manager) {
        case 'user':
          label = 'User'
          break
        case 'manager':
          label = 'Manager'
          break
        case 'managerLevel2':
          label = 'Manager Level 2'
          break
        case 'managerLevel3':
          label = 'Manager Level 3'
          break
        default:
          label = 'Select'
      }
      return label
    },
    handleDropdownOptionDisabled(e, item, items, index) {
      if (e) {
        let mangerList = []
        items.templateList.forEach((element, i) => {
          if (index !== i) mangerList.push(element.manager)
        })
        item.toDataList.forEach(element => {
          if (mangerList.includes(element.value)) {
            element.disabled = true
          }
          if (!mangerList.includes(element.value)) {
            element.disabled = false
          }
        })
      }
    },
    initDropdownOptionDisabled(selfItem, items, index) {
      items.forEach((element, i) => {})
    },
    openContent(list, index) {
      if (list.hasOwnProperty('dis') && list.dis) {
        this.$set(list, 'dis', false)
      } else this.$set(list, 'dis', true)
    },
    templateIdChange(val, item, index, i) {
      item['TemplateIds'] = val
      item[this.scriptItem.templateFields] = this.selectDataObj[
        `${this.scriptItem.text}ListsOrigin`
      ].find(e => e[this.scriptItem.templateFieldValue] === val).template
      this.$nextTick(()=>{
        this.$refs[`myTextEditor${index}${i}`][0].retryRender(
        item[this.scriptItem.templateFields]
      )
      })
    },
    addItem(index, obj) {
      if (obj.length < 3) {
        let a = []
        let temp = JSON.parse(
          JSON.stringify({ ...this.scriptItem.defaultValue[0] })
        )
        obj.forEach(element => {
          a.push(element.manager)
        })
        temp[this.scriptItem.templateMultipleText][0].toDataList.forEach(
          element => {
            if (a.includes(element.value)) element.disabled = true
          }
        )
        obj.push(temp[this.scriptItem.templateMultipleText][0])
      }
    },
    deleteItem(i, obj, items, index) {
      obj.splice(i, 1)
      this.returnAllManager(items)
    },
    getTemplateContent(item) {
      try {
        return this.selectDataObj[`${this.scriptItem.text}ListsOrigin`].find(
          e =>
            e[this.scriptItem.templateFieldValue] ===
            item[this.scriptItem.templateFields]
        ).template
      } catch (error) {
        return null
      }
    },
    comForLists(e, index, obj) {
      if (!e) {
        return false
      }
      let lastList = []
      let selectedList = obj || []
      let originList = this.scriptItem.toDataList || []
      if (Array.isArray(selectedList)) {
        for (let j = 0; j < originList.length; j++) {
          const originItem = originList[j]
          if (
            selectedList.findIndex(
              e =>
                e[this.scriptItem.toFields] ===
                originItem[this.scriptItem.toFieldValue]
            ) === -1
          ) {
            lastList.push(originItem)
          }
        }
      }
      try {
        if (selectedList[index][this.scriptItem.toFields]) {
          let temp = originList.find(
            e =>
              selectedList[index][this.scriptItem.toFields] ===
              e[this.scriptItem.toFieldValue]
          )
          temp && lastList.push(temp)
        }
      } catch (error) {}
      this.forLists = lastList
    },
    addModuleItem(index) {
      let itemTemp = JSON.parse(
        JSON.stringify({ ...this.scriptItem.defaultValue[0] })
      )
      itemTemp.templateList[0].TemplateIds = ''
      itemTemp.templateList[0].templateContent = '';
      this.dataForm[this.scriptItem.text][0]&&(itemTemp[this.scriptItem.dateFields] = this.dataForm[this.scriptItem.text][0][this.scriptItem.dateFields]);
      this.dataForm[this.scriptItem.text].push(itemTemp)  
    },
    deleteModuleItem(index) {
      this.dataForm[this.scriptItem.text].splice(index, 1)
    }
  }
}
</script>

<style lang="scss">
.cycle_label_multiple {
  .label_multiple_header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: absolute;
    right: 0px;
    top: -28px;
    .lable_content {
      margin-bottom: 10px;
    }
  }
  > div:nth-child(2) {
    width: 355px;
    font-size: 14px;
    font-weight: 400;
    color: #7f7f7f;
    line-height: 20px;
    margin-bottom: 10px;
  }
  .cycleMultiple {
    .cycle_multiple_cont {
      background: #ffffff;
      box-shadow: 1px 2px 8px -1px rgba(158, 158, 158, 0.15);
      border-radius: 4px;
      border: 1px solid rgba(19, 141, 199, 0.02);
      padding: 10px;
    }
    .Multiplelist_list {
      margin-bottom: 10px;
      padding-bottom: 10px;
      box-shadow: 0px 1px 0px 0px #f0f0f0;
      width: 100%;
    }
    .editor_content {
      position: relative;
      background: #f0f0f0;
      border-radius: 0 0 6px 6px;
      padding: 10px;
      padding-top: 0;
      ::v-deep .ql-snow {
        border: 0;
      }
      .ql-toolbar {
        border-bottom: 1px solid #ccc;
      }

      .editor_content_template {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
        .el-input__inner {
          background-color: transparent;
          border: 0;
          padding: 0;
        }
        input {
          border: none;
          &::-webkit-input-placeholder {
            color: $--theme-color !important;
          }
        }
      }
      .ql-snow {
        padding: 0 20px;
        & .ql-tooltip {
          z-index: 1;
          left: 10px !important;
        }
        &.ql-toolbar button,
        & .ql-toolbar button,
        & .ql-color-picker,
        & .ql-icon-picker {
          width: 14px;
          height: 14px;
          padding: 0;
          & svg {
            float: left;
          }
        }
        & .ql-picker-label {
          padding: 0;
          border: none;
          float: left;
        }
        & .ql-formats {
          margin-right: 20px;
          & button {
            margin-right: 20px;
            &:last-child {
              margin-right: 0;
            }
          }
        }
      }
      .insert-token {
        position: absolute;
        right: 20px;
        top: 4px;
        width: 30px;
        height: 30px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
    .Multiplelist_form_list {
      padding-bottom: 10px;
      width: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      .add_message {
        width: 100px;
        background: #138dc7;
        border-radius: 2px;
        font-size: 12px;
        font-weight: 400;
        color: #ffffff;
        padding: 0px 10px;
        cursor: pointer;
        line-height: 32px;
        text-align: center;
        background-image: url('../../../assets/ticket/company_watch/add_company_watch.png');
        background-repeat: no-repeat;
        background-size: 12px;
        background-position: 10px center;
      }
      ::v-deep .el-input__inner {
        border: 0;
      }
    }
    .form_list_template {
      width: 100%;
      background: #f0f0f0;
      border-radius: 6px 6px 0 0;
      padding: 7px 0;
      .el-input__inner {
        border: 0;
        background-color: transparent;
      }
      .item_template_box_email {
        display: block;
        .item_template:first-child {
          margin-top: 20px;
        }
        .deleteTemplate {
          width: 14px;
          height: 14px;
          position: absolute;
          right: 15px;
          background: url('../../../assets/mspbots/qa-bot/delete_item_template.png');
          background-repeat: no-repeat;
          background-position: center;
          background-size: 14px;
        }
      }
      .item_template_box_teams {
        display: flex;
        .deleteTemplate {
          width: 14px;
          height: 14px;
          position: absolute;
          right: 15px;
          background: url('../../../assets/mspbots/qa-bot/delete_item_template.png');
          background-repeat: no-repeat;
          background-position: center;
          background-size: 14px;
        }
      }
    }
    .font_weight {
      font-size: 14px;
      font-weight: 600;
      color: #138dc7;
      line-height: 20px;
      margin: 0 5px;
    }
    .label_intro {
      width: 550px;
      font-size: 14px;
      font-weight: 400;
      color: #7f7f7f;
      line-height: 20px;
      margin-bottom: 10px;
    }
    .for-item {
      // border: 1px solid #dfdfdf;
      border-radius: 6px;
      // padding: 10px;
      margin-bottom: 15px;
    }
    .el-form--inline .el-form-item {
      display: inline-flex !important;
      margin-bottom: 0 !important;
    }
    .el-form-item__label {
      font-weight: normal !important;
      padding-bottom: 0;
    }
    .triggedWrap {
      margin-bottom: 10px;
      .Multiplelist_label {
        .Multiplelist_label_header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;
          .laber_text {
            font-size: 16px;
            font-weight: 600;
            color: rgba(0, 0, 0, 0.75);
          }
          .label_header_rg {
            background: url('../../../assets/mspbots/qa-bot/escalation_delete.png');
            background-repeat: no-repeat;
            background-size: 14px;
            background-position: center;
            background-color: transparent;
            button {
              border: 0;
              background-color: transparent;
            }
          }
        }
      }
      .Multiplelist_label_content {
        padding: 10px;
        background: #e6f7ff;
        border-radius: 4px;
        font-size: 14px;
        font-weight: 400;
        color: #138dc7;
        line-height: 20px;
      }
    }
    .moduleBtn {
      text-align: right;
      padding: 0 10px 10px 0;
    }
    .list {
      border-bottom: 1px solid #dfdfdf;
      border-radius: 6px;
      .for-item {
        border-bottom: 1px dashed #dfdfdf;
        padding: 10px 10px 0 10px;
        margin-bottom: 15px;
        &:last-child {
          border-bottom: none;
          margin-bottom: 0;
        }
      }
    }

    .add_new_program {
      button {
        width: 154px;
        height: 32px;
        background: #138dc7;
        border-radius: 2px;
        font-size: 12px;
        font-weight: 400;
        color: #ffffff;
      }
    }
  }
}
.insert_token_pop {
  .token-list {
    max-height: 300px;
    overflow: auto;
    &-item {
      .group-title {
        color: rgba(0, 0, 0, 0.5);
        font-size: 12px;
        width: 100%;
        height: 30px;
        line-height: 30px;
        margin-top: 10px;
      }
      .group-item {
        height: 34px;
        line-height: 34px;
        padding: 0 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        cursor: pointer;
        &:hover {
          background: #f5f7fa;
        }
      }
      .group-item11 {
        display: flex;
        height: 34px;
        line-height: 34px;
        padding: 0 10px;
        cursor: pointer;
        &:hover {
          background: #f5f7fa;
        }
      }
    }
  }
}
</style>
